<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto layout-padding-view">
			<TableSearch :search="state.tableData.search" @search="onSearch" />
			<el-table @selection-change="handleSelectionChange" :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%" stripe>
				<el-table-column type="selection" width="55" />
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="experimentId" label="实验编号" show-overflow-tooltip></el-table-column>
				<el-table-column prop="experimentName" label="实验名称" show-overflow-tooltip></el-table-column>
				<el-table-column prop="studentId" label="学号" show-overflow-tooltip></el-table-column>
				<el-table-column prop="studentName" label="学生姓名" show-overflow-tooltip></el-table-column>
				<el-table-column prop="class" label="班级" show-overflow-tooltip></el-table-column>
				<el-table-column prop="file" label="实验报告" show-overflow-tooltip>
					<template #default="scope">
						<el-tag v-if="scope.row.file === '尚未上传'" type="danger" effect="dark" disable-transitions>
							{{ scope.row.file }}
						</el-tag>
						<el-button v-if="scope.row.file !== '尚未上传'" type="primary" dark @click="onPreview(scope.row.file)"> 预览 </el-button>
					</template>
				</el-table-column>
				<el-table-column prop="teacherGrade" label="教师评分" show-overflow-tooltip>
					<template #default="scope">
						<el-tag v-if="scope.row.teacherGrade === '尚未评分'" type="danger" effect="dark" disable-transitions>
							{{ scope.row.teacherGrade }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="100">
					<template #default="scope">
						<el-button v-if="scope.row.teacherGrade === '尚未评分'" size="small" text type="primary" @click="onOpenEditRole(scope.row)">评分</el-button>
						<el-button v-if="scope.row.teacherGrade !== '尚未评分'" size="small" text type="primary" disabled>已评分</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="table-footer mt15">
				<el-pagination
					@size-change="onHandleSizeChange"
					@current-change="onHandleCurrentChange"
					class="mt15"
					:pager-count="5"
					:page-sizes="[10, 20, 30]"
					v-model:current-page="state.tableData.param.pageNum"
					background
					v-model:page-size="state.tableData.param.pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="state.tableData.total"
				>
				</el-pagination>
				<div class="table-footer-tool">
					<SvgIcon
						name="iconfont icon-yunxiazai_o"
						:size="22"
						title="导出"
						@click="onDownload"
						v-loading.fullscreen.lock="fullscreenLoading"
						:element-loading-text="'数据加载中,请稍后...'"
					/>
				</div>
			</div>
		</div>
		<RoleDialog ref="roleDialogRef" @refresh="getTableData()" />
		<div v-show="state.tableData.ifPreview" class="docx-preview">
			<el-button dark type="primary" @click="state.tableData.ifPreview = false">关闭预览</el-button>
			<vue-office-docx :src="state.tableData.file"></vue-office-docx>
		</div>
	</div>
</template>

<script setup lang="ts" name="gradeManagement">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
const stores = useUserInfo();
const { userInfos } = storeToRefs(stores);
import { gradeInfo, getGradeInfo, downloadGradeInfo } from '/@/api/grade';
import VueOfficeDocx from '@vue-office/docx';
import '@vue-office/docx/lib/index.css';
import { saveAs } from 'file-saver';
import JSZip from 'jszip';
import { stat } from 'fs';
import { stringToBlob } from '/@/utils/blob';

// 引入组件
const RoleDialog = defineAsyncComponent(() => import('/@/views/grade/management/dialog.vue'));
const TableSearch = defineAsyncComponent(() => import('/@/views/grade/management/search.vue'));

// 定义变量内容
const fullscreenLoading = ref(false);
const roleDialogRef = ref();
const state = reactive({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			search: '',
			pageNum: 1,
			pageSize: 10,
		},
		search: [
			{ label: '实验编号', prop: 'experimentId', placeholder: '请输入想查询的实验编号', required: false, type: 'input' },
			{ label: '实验名称', prop: 'experimentName', placeholder: '请输入想查询的实验名称', required: false, type: 'input' },
			{ label: '学号', prop: 'studentId', placeholder: '请输入想查询的学号', required: false, type: 'input' },
			{ label: '学生姓名', prop: 'studentName', placeholder: '请输入想查询的学生姓名', required: false, type: 'input' },
			{ label: '班级', prop: 'class', placeholder: '请输入想查询的班级', required: false, type: 'input' },
		],
		file: '',
		ifPreview: false,
		selectList: [],
		searchData: {
			experiment_id: '',
			experiment_name: '',
			student_id: '',
			student_name: '',
			lesson_name: '',
		},
	},
});
// 初始化表格数据
const getTableData = () => {
	state.tableData.loading = true;
	state.tableData.data = [];
	gradeInfo({ Page: state.tableData.param.pageNum, teacher_id: userInfos.value.Id })
		.then((res) => {
			if (res.code === '2000') {
				state.tableData.data = res.data.map((item: any) => {
					return {
						experimentId: item.experiment_id,
						experimentName: item.experiment_name,
						studentId: item.student_id,
						studentName: item.student_name,
						class: item.lesson_name,
						file: item.file === null ? '尚未上传' : item.file,
						teacherGrade: item.teacher_grade === -1 ? '尚未评分' : item.teacher_grade,
					};
				});
				state.tableData.total = res.totalCount;
			}
		})
		.catch(() => {
			ElMessage.error('请求数据失败');
		});
	setTimeout(() => {
		state.tableData.loading = false;
	}, 500);
};
// 打开修改角色弹窗
const onOpenEditRole = (row: Object) => {
	roleDialogRef.value.openDialog(row);
};
// 分页改变
const onHandleSizeChange = (val: number) => {
	state.tableData.param.pageSize = val;
	getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.tableData.param.pageNum = val;
	getTableData();
};
// 搜索
const onSearch = (data: any) => {
	state.tableData.searchData = data;
	getGradeInfo({
		Page: state.tableData.param.pageNum,
		experiment_id: data.experimentId === '' ? '' : data.experimentId,
		experiment_name: data.experimentNmae === undefined ? '' : data.experimentNmae,
		student_id: data.studentId === '' ? '' : data.studentId,
		student_name: data.studentName === '' ? '' : data.studentName,
		lesson_name: data.class === '' ? '' : data.class,
	})
		.then((res) => {
			if (res.code === '2000') {
				state.tableData.data = res.data.map((item: any) => {
					return {
						experimentId: item.experiment_id,
						experimentName: item.experiment_name,
						studentId: item.student_id,
						studentName: item.student_name,
						class: item.lesson_name,
						file: item.file === null ? '尚未上传' : item.file,
						teacherGrade: item.teacher_grade === -1 ? '尚未评分' : item.teacher_grade,
					};
				});
				state.tableData.total = res.totalCount;
			} else {
				ElMessage.error('请求数据失败!');
			}
		})
		.catch((err) => {
			ElMessage.error('请求数据失败!');
		});
};
// 预览
const onPreview = (data: any) => {
	state.tableData.file = data;
	state.tableData.ifPreview = true;
};
// 多选
const handleSelectionChange = (val: any) => {
	state.tableData.selectList = val;
};
// 下载
const onDownload = () => {
	let total = 0;
	setTimeout(() => {
		if (state.tableData.selectList.length === 0) {
			ElMessage.error('请选择需要下载的实验文件!');
		} else {
			fullscreenLoading.value = true;
			if (Object.values(state.tableData.searchData).every((value) => !value)) {
				let zip = new JSZip();
				state.tableData.selectList.forEach((item: any) => {
					zip.file(item.studentId + '_' + item.class + '_' + item.studentName + '_' + item.experimentName + '.docx', stringToBlob(item.file));
				});
				zip.generateAsync({ type: 'blob' }).then((content) => {
					saveAs(content, '实验文件.zip');
					fullscreenLoading.value = false;
				});
			} else {
				downloadGradeInfo(state.tableData.searchData)
					.then((res) => {
						if (res.code === '2000') {
							total = res.totalCount;
							state.tableData.selectList = res.data;
							let zip = new JSZip();
							state.tableData.selectList.forEach((item: any) => {
								zip.file(item.student_id + '_' + item.class + '_' + item.student_name + '_' + item.experiment_name + '.docx', stringToBlob(item.file));
							});
							zip.generateAsync({ type: 'blob' }).then((content) => {
								saveAs(content, '实验文件.zip');
								fullscreenLoading.value = false;
							});
						} else if (res.data.length === 0) {
							ElMessage.error('没有找到需要下载的实验文件!');
							fullscreenLoading.value = false;
						} else {
							ElMessage.error('请求数据失败!');
							fullscreenLoading.value = false;
						}
					})
					.catch((err) => {
						ElMessage.error('请求数据失败!' + err);
						fullscreenLoading.value = false;
					});
			}
		}
	}, 2000);
};
// 页面加载时
onMounted(() => {
	getTableData();
});
</script>

<style scoped lang="scss">
.system-role-container {
	.system-role-padding {
		padding: 15px;
		.el-table {
			flex: 1;
		}
	}
	.docx-preview {
		overflow: auto;
	}
	.table-footer {
		display: flex;
		.table-footer-tool {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			i {
				margin-right: 10px;
				cursor: pointer;
				color: var(--el-text-color-regular);
				&:last-of-type {
					margin-right: 0;
				}
			}
		}
	}
}
</style>
